<?php


require('phpquery/phpQuery/phpQuery.php');


/*
 * 抓取企业微信的文档保存到目录中,并提交git
 * 2022-04-15 第二个版本;
 */
class Parse2
{
    static $total = 0;
	public static function thislog($info) {
		$logInfo = date('Y-m-d H:i:s ') . $info . "\n";
		file_put_contents("info.log", $logInfo, FILE_APPEND);
		echo $logInfo;
	}

	public static function getJson($docId) {
		self::$total ++;
        // https://developer.work.weixin.qq.com/document/path/93338
		$fileName = "https://developer.work.weixin.qq.com/document/path/" . $docId;
		phpQuery::newDocumentFile($fileName);
		foreach(pq('script') as $key=>$one) {
			$content = pq($one)->html();
			if(strpos($content, "window.__INITIAL_STATE__=") !== false) {
				$content = explode("window.__INITIAL_STATE__=", $content)[1];
				$arr = json_decode( $content, true );
				return $arr;
			}
		}
        return null;
	}

	public static function parseDoc($docId) {
		$arr = self::getJson($docId);
		// file_put_contents("tmpFile.json", json_encode($arr['preDoc']['content_html'], JSON_PRETTY_PRINT | 320));
		$content = $arr['docCnt']['content_md'];
        $content = str_replace('\r\n', "\n", $content);
        $content = str_replace('&quot;', '"', $content);
        self::thislog(self::$total . ",docId:" . $docId . ",length:" . strlen($content));
		return $content;
	}

	public static function asyncDir($pre, $one, $dept=0) {
        // type = 0 目录, 1 文档;
        // 因为能准确判断目录和文档, 就不用过滤层数了;
//        if($dept>4) {
//            return;
//        }
		$one['title'] = str_replace("/", "-", $one['title']);
		$dirName = $pre . "/" . $one['title'] . "." . $one['category_id'];
        self::thislog("dir:" . $dirName);
        // 有children就是目录;
		if(isset($one['children'])) {
			if(!is_dir($dirName)){
				mkdir($dirName);
			}
			if($one['children']) {
				foreach($one['children'] as $two) {
                    self::asyncDir($dirName, $two, $dept+1);
				}
			}
		} else if($one['type'] == 0) {
            return;
		} else {
			$fileName = $dirName. ".md";
			$content = self::parseDoc($one['category_id']);
			if( $content != "" && (!is_file($fileName) || file_get_contents($fileName) != $content )) {
				file_put_contents($fileName, $content);
			} else {
                self::thislog("no update:". $one['category_id']);
			}
		}
	}

	public static function parsePath() {
        self::thislog("start to deal.");
		// 获取定级目录
		$arr = json_decode(file_get_contents("other/content3.json"), true);
		// catagoriesList 处理分类
		// catagoriesMap 分类信息
		// preDoc 展示文档
		$pre = "data";
		foreach($arr['treeOrigin']['children'] as $one) {
			self::asyncDir($pre, $one, 0);
		}
        self::thislog("finish to deal.");
	}
}
